package com.dm.wallpaper.library.adapters;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.helpers.AnimatorHelp;
import com.dm.wallpaper.library.utils.Log;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.utils.ImageSize;
import com.dm.wallpaper.library.utils.Toast;
import com.dm.wallpaper.library.utils.SystemUtils;
import com.dm.wallpaper.library.utils.DialogUtils;
import com.dm.wallpaper.library.utils.WallpaperDownloader;
import com.nostra13.universalimageloader.core.ImageLoader;
import ohos.agp.animation.Animator;
import ohos.agp.components.*;
import ohos.agp.components.element.VectorElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.bundle.IBundleManager;

import java.util.List;

public class LatestListProvider extends RecycleItemProvider {

    private List<Wallpaper> data;

    private LayoutScatter layoutScatter;

    private Context mContext;


    public LatestListProvider(Context context, List<Wallpaper> data) {
        this.mContext = context;
        this.data = data;
        this.layoutScatter = LayoutScatter.getInstance(context);
    }

    @Override
    public int getCount() {
        int count = data != null ? data.size() : 0;
        Log.i("LatestListProvider.getCount([]):46     " + count);
        return count;
    }

    @Override
    public Object getItem(int i) {
        return data != null ? data.get(i) : null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder = null;
        if (component == null) {
            component = layoutScatter.parse(ResourceTable.Layout_latest_item_layout, null, false);
            viewHolder = new ViewHolder((ComponentContainer) component);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) component.getTag();
        }
        Wallpaper wallpaper = data.get(position);
        viewHolder.tvItemName.setText(wallpaper.getName());
        viewHolder.tvItemAuthor.setText(wallpaper.getAuthor());

        Log.i("LatestListProvider.getComponent([position, component, componentContainer]):72");
//        int localId = wallpaper.getLocalid();
//        if (localId == 0) {
//            //  viewHolder.image.setLayoutConfig(layoutConfig);
//            viewHolder.image.setImageAndDecodeBounds(0);
//        } else {
//            // image_wallpaper_show.setLayoutConfig(layoutConfig);
//            viewHolder.image.setImageAndDecodeBounds(localId);
//        }

        ImageLoader.getInstance().displayImage(wallpaper.getUrl(), viewHolder.image);

        viewHolder.imageFavorite.setClickedListener(component1 -> {
            int favorite = wallpaper.getFavorite();
            int setFavorite = favorite == 1 ? 0 : 1;
            wallpaper.setFavorite(setFavorite);
//            DataProvider.getInstance().favoriteWallpaper(wallpaper.getLocalid(), setFavorite);
            setFavorite((Image) component1, Color.WHITE, position, true);
        });

        setFavorite(viewHolder.imageFavorite, Color.WHITE, position, false);

        viewHolder.imageApply.setClickedListener(component2 -> {
            DialogUtils.getInstance().showDialog(component2, wallpaper);
        });

        viewHolder.imageDownload.setClickedListener(component3 -> {
            download(wallpaper);
        });

        ImageSize dimensions = wallpaper.getDimensions();
        resetImageViewHeight(viewHolder.image, dimensions);

        return component;
    }

    private void resetImageViewHeight(Image imageView, ImageSize imageSize) {
        if (imageSize == null) imageSize = new ImageSize(400, 300);
        ComponentContainer.LayoutConfig layoutConfig = imageView.getLayoutConfig();
        int width = SystemUtils.getDisplayWidthInPx(mContext);
        double scaleFactor = (double) width / (double) imageSize.getWidth();
        double measuredHeight = (double) imageSize.getHeight() * scaleFactor;
        int height = Double.valueOf(measuredHeight).intValue();
        layoutConfig.width = width;
        layoutConfig.height = height;
        imageView.setLayoutConfig(layoutConfig);
        Log.i("hh", "imageSize-- " + imageSize.toString());
    }

    private void download(Wallpaper wallpaper) {
        //
        boolean p1 = mContext.verifySelfPermission("ohos.permission.READ_USER_STORAGE") == IBundleManager.PERMISSION_GRANTED;
        boolean p2 = mContext.verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") == IBundleManager.PERMISSION_GRANTED;
        boolean p3 = mContext.verifySelfPermission("ohos.permission.WRITE_MEDIA") == IBundleManager.PERMISSION_GRANTED;
        boolean p4 = mContext.verifySelfPermission("ohos.permission.READ_MEDIA") == IBundleManager.PERMISSION_GRANTED;
        if (p1 && p2 && p3 && p4) {
            //开始下载
            WallpaperDownloader.prepare(mContext).wallpaper(wallpaper).start();
        } else {
            boolean c = mContext.canRequestPermission("ohos.permission.WRITE_USER_STORAGE");
            if (c) {
                String[] per = {"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_MEDIA",
                        "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_USER_STORAGE"};
                mContext.requestPermissionsFromUser(per, 1000);
            } else {
                String promission = SystemUtils.getString(mContext, ResourceTable.String_permission_storage_denied);
                Log.i("LatestListProvider.download([wallpaper]):138    " + promission);
                Toast.show(mContext, promission);
            }
        }
    }


    private void setFavorite(Image imageView, Color color, int position, boolean animate) {
        if (position < 0 || position > data.size()) return;
        Wallpaper wallpaper = data.get(position);
        boolean isFavorite = wallpaper.getFavorite() == 1;
        if (animate) {
            try {
                String string = mContext.getResourceManager().getElement(isFavorite ?
                        ResourceTable.String_wallpaper_favorite_added :
                        ResourceTable.String_wallpaper_favorite_removed).getString(wallpaper.getName());
                Toast.show(mContext, string, LayoutAlignment.BOTTOM);
            } catch (Exception e) {
                e.printStackTrace();
            }
            AnimatorHelp.scaleXYAnimator(imageView, new AnimatorHelp.SimpleStateChangedListener() {
                @Override
                public void onStart(Animator animator) {
                    VectorElement vectorElement = new VectorElement(mContext, isFavorite ? ResourceTable.Graphic_svg_toolbar_love : ResourceTable.Graphic_svg_toolbar_unlove);
                    imageView.setImageElement(vectorElement);
                }
            });
        } else {
            VectorElement vectorElement = new VectorElement(mContext, isFavorite ? ResourceTable.Graphic_svg_toolbar_love : ResourceTable.Graphic_svg_toolbar_unlove);
            imageView.setImageElement(vectorElement);
        }
    }


    static class ViewHolder {

        Text tvItemName;
        Text tvItemAuthor;
        Image image;
        Image imageFavorite;
        Image imageApply;
        Image imageDownload;

        public ViewHolder(ComponentContainer componentContainer) {
            tvItemName = (Text) componentContainer.findComponentById(ResourceTable.Id_tv_name);
            tvItemAuthor = (Text) componentContainer.findComponentById(ResourceTable.Id_tv_author);
            image = (Image) componentContainer.findComponentById(ResourceTable.Id_iv_image);
            imageFavorite = (Image) componentContainer.findComponentById(ResourceTable.Id_iv_favorite);
            imageApply = (Image) componentContainer.findComponentById(ResourceTable.Id_iv_apply);
            imageDownload = (Image) componentContainer.findComponentById(ResourceTable.Id_iv_download);

        }
    }
}
